package db.migration;

import net.jiastudy.biz.user.entity.Role;
import net.jiastudy.biz.user.service.RoleService;
import net.jiastudy.core.base.BaseMigration;
import net.jiastudy.core.common.SysRole;
import net.jiastudy.core.utils.SpringUtility;

import java.util.HashSet;
import java.util.Set;

public class V1_0_7__init_role extends BaseMigration {
    private RoleService roleService = SpringUtility.getBean(RoleService.class);

    @Override
    public void migrate() throws Exception {
        Set<String> permissions = new HashSet<>();
        permissions.add("task:menu");
        permissions.add("task:show");
        permissions.add("task:statistics");

        permissions.add("assessment:menu");
        permissions.add("dept:assessment:audit");
        this.createRole(SysRole.ROLE_USER, permissions);

        Set<String> permissions1 = new HashSet<>();
        permissions1.add("task:menu");
        permissions1.add("task:year");
        permissions1.add("task:enter");
        permissions1.add("task:audit");
        permissions1.add("task:statistics");

        permissions1.add("assessment:menu");
        permissions1.add("dept:assessment:manage");
        permissions1.add("dept:assessment:audit");

        permissions1.add("project:menu");
        permissions1.add("project:dept:manage");
        permissions1.add("project:dept:search");

        permissions1.add("system:menu");
        permissions1.add("system:dept");
        permissions1.add("system:user");
        permissions1.add("system:role");
        this.createRole(SysRole.ROLE_FACULTY, permissions1);
        this.createRole(SysRole.ROLE_QUALITY_CONTROL, permissions1);


        Set<String> permissions3 = new HashSet<>();
        permissions3.add("task:menu");
        permissions3.add("task:dept");
        permissions3.add("task:statistics");
        permissions3.add("task:audit");

        permissions3.add("assessment:menu");
        permissions3.add("dept:assessment:audit");

        permissions3.add("project:menu");
        permissions3.add("project:dept:manage");
        permissions3.add("project:dept:search");

        this.createRole(SysRole.ROLE_DEPT_LEADER, permissions3);
    }

    private void createRole(SysRole sysRole, Set<String> permissions) {
        Role role = new Role();
        role.setCode(sysRole.name());
        role.setName(sysRole.getDesc());
        role.setPermissions(permissions);
        role.setSysRole(false);
        if (roleService.checkCodeExists(sysRole.name(), null)) {
            Role dbRole = roleService.getRoleByCode(sysRole.name());
            role.setId(dbRole.getId());
            roleService.updateRole(role);
        } else {
            roleService.createRole(role);
        }
    }
}
